console.log("华海报表助手 content.js 已加载");

// --- 全局变量存储统计结果 ---
let inVehicleCount = 0;
let outVehicleCount = 0;
let isFetching = false; // 防止重复触发
let alertThreshold = 95; // 告警阈值，接近100时触发
let alarmActive = false; // 告警状态

// --- 新增：提取 Session ID 的函数 ---
function extractSessionId() {
    try {
        const htmlContent = document.documentElement.outerHTML;
        const regex = /FR\.SessionMgr\.register\s*\(\s*'(\d+)'\s*,/i;
        const match = htmlContent.match(regex);

        if (match && match[1]) {
            console.log("成功提取 Session ID:", match[1]);
            return match[1];
        } else {
            console.error("未能从页面HTML中提取 Session ID！检查 FR.SessionMgr.register 调用格式或时机。");
            return null;
        }
    } catch (e) {
        console.error("提取 Session ID 时发生异常:", e);
        return null;
    }
}

// --- 1. 创建/更新显示区域 ---
function createOrUpdateDisplayArea(text) {
    let displayDiv = document.getElementById('vehicle-count-display');
    if (!displayDiv) {
        displayDiv = document.createElement('div');
        displayDiv.id = 'vehicle-count-display';
        displayDiv.style.position = 'fixed';
        displayDiv.style.top = '10px';
        displayDiv.style.right = '10px';
        displayDiv.style.padding = '10px 15px';
        displayDiv.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
        displayDiv.style.border = '1px solid #ccc';
        displayDiv.style.borderRadius = '5px';
        displayDiv.style.zIndex = '9999';
        displayDiv.style.fontSize = '16px';
        displayDiv.style.color = '#333';
        displayDiv.style.fontFamily = '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'; // 更现代的字体
        displayDiv.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)'; // 添加一点阴影
        displayDiv.style.transition = 'background-color 0.5s ease'; // 平滑过渡效果
        document.body.appendChild(displayDiv);
        console.log("显示区域已创建");
    } else {
        // 如果已存在，清除可能存在的告警样式
        if (!alarmActive) {
             resetAlarmStyles(displayDiv);
        }
    }
    displayDiv.textContent = text;
    return displayDiv;
}

// --- 2. 查找并点击查询按钮 (Now responsible for initiating extraction and fetch) ---
function clickQueryButton() {
    const queryButton = document.querySelector('div[widgetname="FORMSUBMIT0"] button');
    if (queryButton) {
        console.log("找到查询按钮，准备点击:", queryButton);
        createOrUpdateDisplayArea('在校车辆: 点击查询...');
        queryButton.click();
        console.log("查询按钮已点击，等待页面响应并提取 Session ID...");

        // 点击后等待，然后提取ID，再开始抓取
        setTimeout(() => {
            console.log("尝试提取 Session ID...");
            const sessionId = extractSessionId();

            if (sessionId) {
                console.log("提取 Session ID 成功，准备获取数据...");
                const displayArea = createOrUpdateDisplayArea('在校车辆: 开始获取数据...');
                fetchDataAndProcess(displayArea, sessionId);
            } else {
                console.error("点击查询按钮后未能提取 Session ID！");
                createOrUpdateDisplayArea("错误: 未能找到 Session 信息 (点击后)。请刷新重试或联系开发者。");
            }
        }, 3000); // <--- 增加等待时间至 3000 毫秒

        return true;
    } else {
        console.error("未能找到查询按钮！将在2秒后重试...");
        setTimeout(clickQueryButton, 2000);
        return false;
    }
}

// --- 3. 抓取数据并处理 (Re-applying Optimization: Get total pages first) ---
async function fetchDataAndProcess(displayArea, sessionId) {
    if (!sessionId) {
        createOrUpdateDisplayArea("错误: 未能获取 Session ID");
        console.error("fetchDataAndProcess 调用时未提供 Session ID!");
        return;
    }
    if (isFetching) {
        console.log("已经在抓取数据中，本次跳过");
        return;
    }
    isFetching = true;
    inVehicleCount = 0;
    outVehicleCount = 0;
    alarmActive = false;
    resetAlarmStyles();

    const baseDataUrl = `http://r.huahai.net:8080/HH/Report?__boxModel__=true&op=page_content&sessionID=${sessionId}`;
    let totalPageCount = 0; // Initialize total page count

    console.log("开始获取数据，首先获取第一页并尝试提取总页数...");

    try {
        // --- Step 1: Fetch page 1 and extract total pages ---
        const firstPageUrl = `${baseDataUrl}&_=${Date.now()}&pn=1`;
        createOrUpdateDisplayArea(`在校车辆: 正在获取第 1 页...`);
        console.log(`尝试获取: ${firstPageUrl}`);

        const responsePage1 = await fetch(firstPageUrl);
        if (!responsePage1.ok) {
            // Handle error for the first page request (reuse previous error handling)
             if (responsePage1.status === 401 || responsePage1.status === 403) { 
                 throw new Error(`Session无效或无权限 (状态码: ${responsePage1.status})，提取的Session ID [${sessionId}] 可能已失效`);
            } else if (responsePage1.status === 500) {
                 const errorText = await responsePage1.text();
                 if (errorText.includes("Session过期")) {
                     throw new Error(`服务器明确返回Session过期，提取的Session ID [${sessionId}] 可能已失效`);
                 }
            }
            throw new Error(`获取第一页失败! status: ${responsePage1.status}`);
        }
        const htmlTextPage1 = await responsePage1.text();

        // Attempt to extract total pages
        const totalPageRegex = /FR\._p\.reportTotalPage\s*=\s*(\d+);/i;
        const pageMatch = htmlTextPage1.match(totalPageRegex);
        if (pageMatch && pageMatch[1]) {
            totalPageCount = parseInt(pageMatch[1], 10);
            console.log(`成功提取总页数: ${totalPageCount}`);
        } else {
            console.warn("未能从第一页响应中提取 reportTotalPage，将仅处理第一页数据。");
            // If extraction fails, process only page 1 or throw error
            totalPageCount = 1; // Set to 1 to prevent further looping
            // Or uncomment below to stop execution:
            // throw new Error("无法确定总页数，请检查页面结构或提取逻辑。");
        }

        // Process data from page 1
        const countsPage1 = parseHtmlAndCount(htmlTextPage1);
        console.log(`第 1 页结果: 进=${countsPage1.pageIn}, 出=${countsPage1.pageOut}, 处理行数=${countsPage1.rowsProcessed}`);
        inVehicleCount += countsPage1.pageIn;
        outVehicleCount += countsPage1.pageOut;

        // Update display after page 1
        let currentTotal = inVehicleCount - outVehicleCount;
        let displayText = `在校车辆: ${currentTotal} (进:${inVehicleCount} / 出:${outVehicleCount}) - P1/${totalPageCount || '?'}`; 
        createOrUpdateDisplayArea(displayText);
        checkAndTriggerAlarm(currentTotal, displayArea);

        // --- Step 2: Fetch remaining pages (if total pages > 1) ---
        if (totalPageCount > 1) {
            console.log(`准备获取剩余页 (从 2 到 ${totalPageCount})...`);
            for (let currentPage = 2; currentPage <= totalPageCount; currentPage++) {
                const timestamp = Date.now();
                const url = `${baseDataUrl}&_=${timestamp}&pn=${currentPage}`;
                // Update display to show progress through known total pages
                createOrUpdateDisplayArea(`在校车辆: 正在获取第 ${currentPage}/${totalPageCount} 页...`);
                console.log(`尝试获取: ${url}`);

                const response = await fetch(url);
                if (!response.ok) {
                    console.error(`获取第 ${currentPage} 页失败! status: ${response.status}. 跳过此页.`);
                    continue; // Skip this page on error
                }
                const htmlText = await response.text();
                const counts = parseHtmlAndCount(htmlText);
                console.log(`第 ${currentPage} 页结果: 进=${counts.pageIn}, 出=${counts.pageOut}, 处理行数=${counts.rowsProcessed}`);
                
                // Accumulate counts
                inVehicleCount += counts.pageIn;
                outVehicleCount += counts.pageOut;

                // Update display after each subsequent page
                currentTotal = inVehicleCount - outVehicleCount;
                displayText = `在校车辆: ${currentTotal} (进:${inVehicleCount} / 出:${outVehicleCount}) - P${currentPage}/${totalPageCount}`; 
                createOrUpdateDisplayArea(displayText);

                checkAndTriggerAlarm(currentTotal, displayArea);

                // Short delay
                await new Promise(resolve => setTimeout(resolve, 300));
            }
        }

        // --- Step 3: Final update ---
        const finalTotal = inVehicleCount - outVehicleCount;
        const finalDisplayText = `在校车辆: ${finalTotal} (进:${inVehicleCount} / 出:${outVehicleCount}) - 完成 (${totalPageCount}页)`;
        createOrUpdateDisplayArea(finalDisplayText);
        checkAndTriggerAlarm(finalTotal, displayArea);
        console.log(`数据抓取完成。总计: 进=${inVehicleCount}, 出=${outVehicleCount}, 在校=${finalTotal}`);

    } catch (error) {
        console.error("数据抓取或处理过程中发生错误:", error);
        let errorMsg = error.message;
        if (errorMsg.includes("Session")) {
             errorMsg += "\n请尝试刷新页面重试。如果问题持续，可能是Session ID提取逻辑失效。"
        }
        createOrUpdateDisplayArea(`错误: ${errorMsg}`);
    } finally {
        isFetching = false;
    }
}

// --- 4. 解析HTML并统计单页数据 ---
function parseHtmlAndCount(htmlText) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlText, 'text/html');
    let rows = doc.querySelectorAll('div.fr-grid > table > tbody > tr'); 
    if (!rows || rows.length === 0) { 
        rows = doc.querySelectorAll('table tr');
    }

    let pageIn = 0;
    let pageOut = 0;
    let rowsProcessed = 0;

    if (!rows || rows.length === 0) {
        console.log("解析到的HTML中没有找到有效的 <tr> 元素。");
        if (htmlText.includes('"totalPage":0') || htmlText.trim() === "[]" || htmlText.trim() === "{}") {
             console.log("响应内容似乎表明没有更多数据。 ");
             return { pageIn: 0, pageOut: 0, rowsProcessed: 0 };
        }
        console.warn("未找到行且无明确结束标记，可能解析或页面结构问题。 ");
        return { pageIn: 0, pageOut: 0, rowsProcessed: 0 };
    }

    rows.forEach((row, index) => {
        const cells = row.querySelectorAll('td');
        if (row.querySelector('th') || cells.length <= 3) { 
            return; 
        }

        const deviceId = cells[3].textContent.trim();
        if (deviceId === '05868501') {
            pageIn++;
            rowsProcessed++;
        } else if (deviceId === '05868502') {
            pageOut++;
            rowsProcessed++;
        }
    });

    return { pageIn, pageOut, rowsProcessed };
}

// --- 5. 检查并触发告警 ---
function checkAndTriggerAlarm(currentTotal, displayArea) {
    if (currentTotal >= alertThreshold) {
        if (!alarmActive) {
            console.log(`触发告警！当前数量: ${currentTotal} (阈值: ${alertThreshold})`);
            triggerAlarm(displayArea);
            alarmActive = true;
        }
    } else {
        if (alarmActive) {
            console.log("数量低于阈值，解除告警");
            resetAlarmStyles(displayArea);
            alarmActive = false;
        }
    }
}

// --- 6. 触发告警效果 ---
function triggerAlarm(displayArea) {
    // 方式三：创建一个全屏覆盖层（更推荐，不影响原页面布局）
    let overlay = document.getElementById('alarm-overlay');
    if (!overlay) {
        overlay = document.createElement('div');
        overlay.id = 'alarm-overlay';
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = 'rgba(255, 0, 0, 0.15)'; // 半透明红色
        overlay.style.zIndex = '9998'; // 比显示区域低一层
        overlay.style.pointerEvents = 'none'; // 允许点击穿透
        overlay.style.transition = 'opacity 0.5s ease';
        overlay.style.opacity = '0';
        document.body.appendChild(overlay);
        // 渐显效果
        setTimeout(() => { 
            if (document.getElementById('alarm-overlay')) { // 再次检查元素是否存在
                document.getElementById('alarm-overlay').style.opacity = '1'; 
            }
        }, 50);
    } else {
        // 如果覆盖层已存在（可能因为快速触发），确保它是可见的
        overlay.style.opacity = '1';
    }

    // 同时也可以更新显示区域样式，使其更醒目
    if(displayArea) {
        displayArea.style.backgroundColor = 'rgba(255, 69, 0, 0.8)'; // 橙红色背景
        displayArea.style.color = 'white';
        displayArea.style.fontWeight = 'bold';
        displayArea.style.border = '2px solid red';
    }
}

// --- 7. 重置/移除告警效果 ---
function resetAlarmStyles(displayArea) {
    // 移除覆盖层
    let overlay = document.getElementById('alarm-overlay');
    if (overlay) {
        overlay.style.opacity = '0';
        // 等待渐隐动画结束后移除元素
        setTimeout(() => { 
             if (document.getElementById('alarm-overlay')) { // 再次检查
                document.getElementById('alarm-overlay').remove(); 
             }
        }, 500);
    }

    // 重置显示区域样式
    if (displayArea) {
        displayArea.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
        displayArea.style.color = '#333';
        displayArea.style.fontWeight = 'normal';
        displayArea.style.border = '1px solid #ccc';
    }
}

// --- 主逻辑 (Simplified: directly call clickQueryButton) ---
window.addEventListener('load', () => {
    console.log("页面加载完成，开始执行插件逻辑");
    createOrUpdateDisplayArea('在校车辆: 初始化...');

    // Directly call clickQueryButton, which handles the subsequent flow
    clickQueryButton();
});


